package com.itheima.imclient100.view;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itheima.imclient100.BaseActivity;
import com.itheima.imclient100.MainActivity;
import com.itheima.imclient100.R;
import com.itheima.imclient100.presenter.LoginPresenter;
import com.itheima.imclient100.presenter.impl.LoginPresenterImpl;
import com.itheima.imclient100.utils.SPUtils;
import com.itheima.imclient100.utils.Utils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements LoginView{

    @InjectView(R.id.iv_avatar)
    ImageView ivAvatar;
    @InjectView(R.id.et_username)
    EditText etUsername;
    @InjectView(R.id.til_username)
    TextInputLayout tilUsername;
    @InjectView(R.id.et_pwd)
    EditText etPwd;
    @InjectView(R.id.til_pwd)
    TextInputLayout tilPwd;
    @InjectView(R.id.btn_login)
    Button btnLogin;
    @InjectView(R.id.tv_newuser)
    TextView tvNewuser;

    private LoginPresenter  presenter = null;
    private String username;
    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        }

        String password = SPUtils.getPassword(this);
        String username = SPUtils.getUsername(this);
        if(!TextUtils.isEmpty(username)){
            etPwd.setText(password);
            etUsername.setText(username);
        }
        presenter = new LoginPresenterImpl(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        System.out.println("onNewIntent");
//        String username = intent.getStringExtra("username");
//        String pwd = intent.getStringExtra("pwd");
        String password = SPUtils.getPassword(this);
        String username = SPUtils.getUsername(this);
        if(!TextUtils.isEmpty(username)){
            etPwd.setText(password);
            etUsername.setText(username);
        }

    }

    @OnClick({R.id.btn_login, R.id.tv_newuser})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //用户名密码的校验 用户名是字符和数字
                username = etUsername.getText().toString().trim();
                pwd = etPwd.getText().toString().trim();
                // mPresenter.regist();
                if(!Utils.checkUsername(username)){
                    //设置可以显示错误信息的布局
                    tilUsername.setErrorEnabled(true);
                    tilUsername.setError("用户名不合法");
                    return;
                }else{
                    //设置关闭显示错误信息的布局
                    tilUsername.setErrorEnabled(false);
                }


                if(!Utils.checkPassword(pwd)){
                    tilPwd.setErrorEnabled(true);
                    tilPwd.setError("密码不合法");
                    return;
                }else{
                    tilPwd.setErrorEnabled(false);
                }
                login(username,pwd);
               // presenter.login(username,pwd);
                break;
            case R.id.tv_newuser:
                startActivity(new Intent(getApplicationContext(),RegistActivity.class));
                break;
        }
    }

    private void login(String username, String pwd) {
        if(Build.VERSION.SDK_INT>=23){
            //checkSelfPermission 检测自己是否有某个权限   PERMISSION_GRANTED 有权限
            //PERMISSION_DENIED 没有权限
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PermissionChecker.PERMISSION_GRANTED){
                //动态申请权限 requestCode的值一定要>=0  如果<0不会弹出申请权限的对话框
                //第一个参数 权限的数组 一次可以申请多个权限  第二个参数 请求码 需要>=0
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                return;
            }else{
                presenter.login(username,pwd);
            }
        }else{
        presenter.login(username,pwd);
        }
    }

    @Override
    public void getLoginState(boolean isLoggedin, String errMsg) {
        if(isLoggedin){
            //登录成功
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            SPUtils.savePassword(getApplicationContext(),pwd);
            SPUtils.saveUsername(getApplicationContext(),username);
            finish();
        }else{
            //登录失败
            showToast(errMsg);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //调用了requestPermissions 方法 回弹对话框 如果用户操作之后 会走这个回调 返回用户选择的结果
        if(requestCode == 1){
            if(grantResults[0] == PermissionChecker.PERMISSION_GRANTED){
                //如果请求的结果是PERMISSION_GRANTED 说明用户已经授予了权限 可以继续进行操作
                login(username,pwd);
            }else{
                //如果没权限 弹toast提示
                showToast("没有sd卡权限没法保存聊天记录");
            }
        }
    }
}
